package com.utils;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

public class OKHttpClientBuilder {
	
	public static OkHttpClient.Builder buildOKHttpClient() {
		try {
			TrustManager[] trustAllCerts = buildTrustManagers();
			final SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

			final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
			OkHttpClient.Builder builder = new OkHttpClient.Builder();
//			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("", 4587));
//			builder.proxy(proxy);
			builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
			builder.hostnameVerifier((hostname, session) -> true);
			builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
			builder.readTimeout(10000, TimeUnit.MILLISECONDS);
			return builder;
		} catch (NoSuchAlgorithmException | KeyManagementException e) {
			e.printStackTrace();
			return new OkHttpClient.Builder();
		}
	}
	
	public static OkHttpClient.Builder buildOKHttpClientProxy(String host,Integer port) {
		try {
			TrustManager[] trustAllCerts = buildTrustManagers();
			final SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
			
			final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
			OkHttpClient.Builder builder = new OkHttpClient.Builder();
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
			builder.proxy(proxy);
			builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
			builder.hostnameVerifier((hostname, session) -> true);
			builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
			builder.readTimeout(10000, TimeUnit.MILLISECONDS);
			return builder;
		} catch (NoSuchAlgorithmException | KeyManagementException e) {
			e.printStackTrace();
			return new OkHttpClient.Builder();
		}
	}

	private static TrustManager[] buildTrustManagers() {
		return new TrustManager[] { new X509TrustManager() {
			@Override
			public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
			}

			@Override
			public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
			}

			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return new java.security.cert.X509Certificate[] {};
			}
		} };
	}
}
